package org.goodsmanager.controller;

import org.goodsmanager.entity.Order;
import org.goodsmanager.entity.OrderItem;
import org.goodsmanager.entity.User;
import org.goodsmanager.entity.Address;
import org.goodsmanager.entity.Cart;
import org.goodsmanager.service.OrderService;
import org.goodsmanager.service.CartService;
import org.goodsmanager.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private AddressService addressService;
    
    /**
     * 订单确认页面
     */
    @GetMapping("/confirm")
    public String confirmOrder(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 获取购物车商品
        List<Cart> cartItems = cartService.getSelectedCartItems(user.getId());
        if (cartItems.isEmpty()) {
            model.addAttribute("message", "购物车为空，请先添加商品");
            return "shop/cart";
        }
        
        // 计算总金额和总数量
        BigDecimal totalAmount = BigDecimal.ZERO;
        int totalQuantity = 0;
        for (Cart item : cartItems) {
            totalAmount = totalAmount.add(BigDecimal.valueOf(item.getSubtotal()));
            totalQuantity += item.getQuantity();
        }
        
        // 获取用户地址列表
        List<Address> addresses = addressService.getAddressesByUserId(Long.valueOf(user.getId()));
        
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("totalAmount", totalAmount);
        model.addAttribute("totalQuantity", totalQuantity);
        model.addAttribute("addresses", addresses);
        
        return "shop/order-confirm";
    }
    
    /**
     * 提交订单
     */
    @PostMapping("/submit")
    @ResponseBody
    public Map<String, Object> submitOrder(
            @RequestParam Long addressId,
            @RequestParam String paymentMethod,
            @RequestParam(required = false) String remark,
            HttpSession session) {
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            // 获取购物车商品
            List<Cart> cartItems = cartService.getSelectedCartItems(user.getId());
            if (cartItems.isEmpty()) {
                return Map.of("success", false, "message", "购物车为空");
            }
            
            // 获取收货地址
            Address address = addressService.getAddressById(addressId);
            if (address == null || !address.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "收货地址无效");
            }
            
            // 创建订单
            Order order = new Order();
            order.setUserId(Long.valueOf(user.getId()));
            order.setUsername(user.getUsername());
            order.setAddress(address);
            order.setPaymentMethod(paymentMethod);
            order.setRemark(remark);
            
            Order createdOrder = orderService.createOrder(order, cartItems);
            
            // 清空购物车
            cartService.clearCart(user.getId());
            
            return Map.of(
                "success", true,
                "message", "订单创建成功",
                "orderId", createdOrder.getId(),
                "orderNumber", createdOrder.getOrderNumber()
            );
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "订单创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 订单支付页面
     */
    @GetMapping("/pay/{orderId}")
    public String payOrder(@PathVariable Long orderId, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        Order order = orderService.getOrderById(orderId);
        if (order == null || !order.getUserId().equals(user.getId())) {
            return "redirect:/profile";
        }
        
        model.addAttribute("order", order);
        return "shop/order-pay";
    }
    
    /**
     * 处理支付
     */
    @PostMapping("/pay/{orderId}")
    @ResponseBody
    public Map<String, Object> processPayment(
            @PathVariable Long orderId,
            @RequestParam String paymentMethod,
            HttpSession session) {
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            Order order = orderService.getOrderById(orderId);
            if (order == null || !order.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "订单无效");
            }
            
            if (!"pending".equals(order.getStatus())) {
                return Map.of("success", false, "message", "订单状态不正确");
            }
            
            // 模拟支付处理
            String paymentId = "PAY" + System.currentTimeMillis();
            boolean success = orderService.updateOrderPayment(orderId, paymentMethod, paymentId);
            
            if (success) {
                // 更新订单状态为已支付
                orderService.updateOrderStatus(orderId, "paid");
                return Map.of("success", true, "message", "支付成功");
            } else {
                return Map.of("success", false, "message", "支付失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "支付处理失败：" + e.getMessage());
        }
    }
    
    /**
     * 订单详情页面
     */
    @GetMapping("/detail/{orderId}")
    public String orderDetail(@PathVariable Long orderId, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        Order order = orderService.getOrderById(orderId);
        if (order == null || !order.getUserId().equals(user.getId())) {
            return "redirect:/profile";
        }
        
        model.addAttribute("order", order);
        return "shop/order-detail";
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel/{orderId}")
    @ResponseBody
    public Map<String, Object> cancelOrder(@PathVariable Long orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            Order order = orderService.getOrderById(orderId);
            if (order == null || !order.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "订单无效");
            }
            
            if (!"pending".equals(order.getStatus())) {
                return Map.of("success", false, "message", "只能取消待支付订单");
            }
            
            boolean success = orderService.cancelOrder(orderId);
            
            if (success) {
                return Map.of("success", true, "message", "订单已取消");
            } else {
                return Map.of("success", false, "message", "取消订单失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "取消订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 确认收货
     */
    @PostMapping("/confirm/{orderId}")
    @ResponseBody
    public Map<String, Object> confirmReceive(@PathVariable Long orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Map.of("success", false, "message", "请先登录");
        }
        
        try {
            Order order = orderService.getOrderById(orderId);
            if (order == null || !order.getUserId().equals(user.getId())) {
                return Map.of("success", false, "message", "订单无效");
            }
            
            if (!"shipped".equals(order.getStatus())) {
                return Map.of("success", false, "message", "只能确认已发货的订单");
            }
            
            boolean success = orderService.updateOrderStatus(orderId, "delivered");
            
            if (success) {
                return Map.of("success", true, "message", "确认收货成功");
            } else {
                return Map.of("success", false, "message", "确认收货失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("success", false, "message", "确认收货失败：" + e.getMessage());
        }
    }
}